#!/bin/bash

if [ -n "$1" ]
then
	CASSDK_HOME="$1"
else
	##没有指定安装路径时，指定默认的路径 
	CASSDK_HOME="/usr/local/cassdk"
fi
mkdir_if_no_exist(){
	if [ $# -eq 1 ]
	then
		if [[ -d $1 ]]
		then
			return 0
			
		else
			##安装路径不存在时创建目录 
			mkdir $1
		fi
	else 
		echo invalid argument
		return -1
	fi
}
CASSDK_HOME_LIB="$CASSDK_HOME/bin"
if mkdir_if_no_exist $CASSDK_HOME && mkdir_if_no_exist $CASSDK_HOME_LIB
then
	echo "install to CASSDK........................."
	src_path=$(cd "$(dirname "$0")"; pwd)
	cd "$(dirname "$0")"
	echo copy to $CASSDK_HOME_LIB
	chmod +x lib*
	cp -r * $CASSDK_HOME_LIB
	echo "$CASSDK_HOME_LIB">/etc/ld.so.conf.d/cassdk_lib.conf
	/sbin/ldconfig
	echo modify /etc/profile,add $CASSDK_HOME_LIB to LD_LIBRARY_PATH,and define CASSDK_HOME
	new_export="export LD_LIBRARY_PATH=$CASSDK_HOME_LIB:\$LD_LIBRARY_PATH"
	reg_str="^\s*export\s*LD_LIBRARY_PATH=$CASSDK_HOME_LIB:\$LD_LIBRARY_PATH"
	old_path=`sed -nr 's/^\s*export\s*CASSDK_HOME\s*=(.*)$/\1/p' /etc/profile`	
	if [ "$old_path" = "$CASSDK_HOME" ]		
	then
		# 如果已经有CASSDK_HOME就跳过
		echo CASS_HOME defined,skip
	elif [ -n "$old_path" ]
	then	
		# 如果CASSDK_HOME定义不一致则更新
		echo modify CASSDK_HOME
		sed -i_bak -r "s!(^\s*export\s*CASSDK_HOME\s*=).*\$!\\1$CASSDK_HOME!g" /etc/profile
	else		
		# CASSDK_HOME没有定义,则新加一行定义
		echo defined CASSDK_HOME variable
		echo export CASSDK_HOME=$CASSDK_HOME >> /etc/profile
	fi
	if [ -z "$old_path" ]
	then
		old_lib_path=$CASSDK_HOME_LIB	
	else
		old_lib_path="$old_path/bin"
	fi 

	if  grep -q "^\s*export\s*LD_LIBRARY_PATH\s*=$CASSDK_HOME_LIB:\$LD_LIBRARY_PATH" /etc/profile
	then
		# 如果已经有CASSDK_HOME_LIB已经在LD_LIBRARY_PATH中就跳过
		echo $CASSDK_HOME_LIB exists in LD_LIBRARY_PATH,skip
	elif grep -q "^\s*export\s*LD_LIBRARY_PATH\s*=$old_lib_path:\$LD_LIBRARY_PATH" /etc/profile
	then	
		# 如果LD_LIBRARY_PATHＫ中CASSDK_HOME_LIB定义不一致则更新
		echo $old_lib_path exists in LD_LIBRARY_PATH,modify it
		sed -i_bak -r "s!(^\s*export\s*LD_LIBRARY_PATH\s*=)$old_lib_path(.*)\$!\\1$CASSDK_HOME_LIB\\2!g" /etc/profile
	else
		# CASSDK_HOME_LIB没有定义在LD_LIBRARY_PATH,则新加一行定义
		echo defined LD_LIBRARY_PATH variable
		echo $new_export >> /etc/profile
	fi

	# display new line
	grep $reg_str /etc/profile
	grep CASSDK_HOME /etc/profile
	echo variable LD_LIBRARY_PATH and CASSDK_HOME in /etc/profile updated	
	source /etc/profile	
	chown root /usr/local/cassdk/bin/Z2V0bWFj.so
	chmod +s /usr/local/cassdk/bin/Z2V0bWFj.so
	chmod +x /usr/local/cassdk/bin/Z2V0bWFj.so
	echo "install finished"
fi

